package com.xuecheng.media.domain.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.xuecheng.media.domain.mapper.MediaProcessMapper;
import com.xuecheng.media.domain.model.entity.MediaProcessHistory;
import com.xuecheng.media.domain.service.MediaProcessHistoryService;
import com.xuecheng.media.domain.service.MediaProcessService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.media.domain.model.entity.MediaProcess;
import com.xuecheng.media.infrastructure.enums.MediaProcessStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class MediaProcessServiceImpl extends ServiceImpl<MediaProcessMapper, MediaProcess> implements MediaProcessService {

    @Autowired
    private MediaProcessMapper mediaProcessMapper;

    @Autowired
    private MediaProcessHistoryService mediaProcessHistoryService;

    @Override
    public List<MediaProcess> getWaitHandleTaskList(Integer shardIndex, Integer shardTotal, Integer processors) {
        return mediaProcessMapper.getWaitHandleTaskList(shardIndex, shardTotal, processors);
    }

    @Override
    public Boolean startTask(Long taskId) {
        LocalDateTime now = LocalDateTime.now();
        return mediaProcessMapper.startTask(taskId, now) <= 0 ? false : true;
    }


    @Override
    public void updateProcess(MediaProcess mediaProcess) {
        MediaProcess find = mediaProcessMapper.selectById(mediaProcess.getId());
        BeanUtils.copyProperties(mediaProcess, find);
        mediaProcessMapper.updateById(find);

        // 处理成功
        if (find.getStatus().equals(MediaProcessStatusEnum.SUCCESS.getType())){
            // 添加到视频处理历史记录
            mediaProcessHistoryService.save(BeanUtil.copyProperties(find, MediaProcessHistory.class));
            // 删除视频处理表记录
            mediaProcessMapper.deleteById(find.getId());
        } else {
            if (find.getFailCount() == 3){
                // todo 达到最大失败次数，发送邮件提醒工作人员进行人工处理

            }
        }
    }

    @Override
    public List<MediaProcess> getCompensateTaskList(Integer shardIndex, Integer shardTotal, Integer processors) {
        return mediaProcessMapper.getCompensateTaskList(shardIndex, shardTotal, processors);
    }
}
